package com.nursinghome.management.service;

import com.nursinghome.management.model.Admin;
import com.nursinghome.management.model.User;
import com.nursinghome.management.repository.AdminRepository;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class AdminService {

    private final AdminRepository adminRepository;
    private final UserService userService;

    public AdminService(AdminRepository adminRepository, UserService userService) {
        this.adminRepository = adminRepository;
        this.userService = userService;
    }

    public List<Admin> getAllAdmins() {
        return adminRepository.findAll();
    }

    public Admin getAdminById(Long id) {
        return adminRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("Admin not found with id: " + id));
    }

    public Admin getAdminByUser(User user) {
        return adminRepository.findByUser(user)
                .orElseThrow(() -> new RuntimeException("Admin not found for user: " + user.getUsername()));
    }

    public Admin createAdmin(Admin admin) {
        return adminRepository.save(admin);
    }

    public Admin updateAdmin(Admin admin) {
        Admin existingAdmin = adminRepository.findById(admin.getId())
                .orElseThrow(() -> new RuntimeException("Admin not found with id: " + admin.getId()));

        existingAdmin.setDepartment(admin.getDepartment());
        existingAdmin.setPosition(admin.getPosition());

        return adminRepository.save(existingAdmin);
    }

    public void deleteAdmin(Long id) {
        adminRepository.deleteById(id);
    }
}